package com.it.emall.controller;

import com.it.emall.service.LikesService;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/like")
public class LikesController {
    @Autowired
    private LikesService likesService;

    /**
     * 用户点赞
     * @param token
     * @param recipeId
     * @return
     */
    @PostMapping("/toggle")
    public Object toggleLike(@RequestHeader("token") String token, @RequestParam int recipeId) {
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);
        int result = likesService.toggleLike(userId, recipeId);
        if (result == 0) {
            return ResponseUtils.ok("点赞成功");
        } else if (result == 1) {
            return ResponseUtils.ok("取消点赞成功");
        } else {
            return ResponseUtils.fail(500, "点赞操作失败");
        }
    }

    // 查询点赞状态
    @GetMapping("/status")
    public Object checkLikeStatus(@RequestParam Integer recipeId, @RequestHeader("token") String token) {
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);

        if (userId == null) {
            return ResponseUtils.fail(500,"请登入");
        }

        boolean isLiked = likesService.checkLikeStatus(userId, recipeId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("liked", isLiked);
        return ResponseUtils.ok(response);
    }
}
